package com.sqx.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserCertificationService;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.catalina.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@AllArgsConstructor
public class UserCertificationImpl extends ServiceImpl<UserCertificationDao, UserCertification> implements UserCertificationService {
    private UserDao userDao;



    @Override
    public Result insert(Long userId, String name, String idNumber, String front, String back, Integer classify, String phone, String address, String shopImg, String shopName, String addressImg, String startTime, String endTime, String shopType, String longitude, String latitude) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询身份证是否被绑定
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("id_number", idNumber).eq("status", 1));
        if (userCertification != null) {
            return Result.error("身份证号已经被绑定");
        } else {
            //查询是否实名过
            UserCertification userCertification1 = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
            if (userCertification1 == null) {
                //没有实名过
                UserCertification userCertification2 = new UserCertification();
                userCertification2.setUserId(userId);
                userCertification2.setIdNumber(idNumber);
                userCertification2.setName(name);
                userCertification2.setCreateTime(simpleDateFormat.format(new Date()));
                userCertification2.setFront(front);
                userCertification2.setBack(back);
                userCertification2.setStatus((long) 0);
                userCertification2.setUpdateTime(simpleDateFormat.format(new Date()));
                userCertification2.setClassify(classify);
                userCertification2.setPhone(phone);
                userCertification2.setAddress(address);
                userCertification2.setShopImg(shopImg);
                userCertification2.setAddressImg(addressImg);
                userCertification2.setShopName(shopName);
                userCertification2.setShopType(shopType);
                userCertification2.setStartTime(startTime);
                userCertification2.setEndTime(endTime);
                userCertification2.setLatitude(latitude);
                userCertification2.setLongitude(longitude);
                baseMapper.insert(userCertification2);
            } else {
                //实名过
                userCertification1.setName(name);
                userCertification1.setIdNumber(idNumber);
                userCertification1.setFront(front);
                userCertification1.setBack(back);
                userCertification1.setStatus(0L);
                userCertification1.setUpdateTime(simpleDateFormat.format(new Date()));
                userCertification1.setClassify(classify);
                userCertification1.setPhone(phone);
                userCertification1.setAddress(address);
                userCertification1.setShopImg(shopImg);
                userCertification1.setAddressImg(addressImg);
                userCertification1.setShopName(shopName);
                userCertification1.setShopType(shopType);
                userCertification1.setStartTime(startTime);
                userCertification1.setEndTime(endTime);
                userCertification1.setLatitude(latitude);
                userCertification1.setLongitude(longitude);
                baseMapper.updateById(userCertification1);
            }
            return Result.success();
        }
    }


    @Override
    public Result inserts(UserCertification newUserCertification) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询身份证是否被绑定
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("id_number", newUserCertification.getIdNumber()).eq("status", 1));
        if (userCertification != null ) {
            if(newUserCertification.getUserId()!=null){
                if(!newUserCertification.getUserId().equals(userCertification.getUserId())){
                    return Result.error("身份证号已经被绑定");
                }
            }else{
                return Result.error("身份证号已经被绑定");
            }
        }
        //查询是否实名过
        UserCertification userCertification1 = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", newUserCertification.getUserId()));
        if (userCertification1 == null) {
            //没有实名过
            newUserCertification.setCreateTime(simpleDateFormat.format(new Date()));
            newUserCertification.setStatus((long) 0);
            newUserCertification.setOnLine(2);
            newUserCertification.setUpdateTime(simpleDateFormat.format(new Date()));
            baseMapper.insert(newUserCertification);
        } else {
            //实名过
            newUserCertification.setId(userCertification1.getId());
            newUserCertification.setStatus(0L);
            newUserCertification.setOnLine(2);
            newUserCertification.setUpdateTime(simpleDateFormat.format(new Date()));
            baseMapper.updateById(newUserCertification);
        }
        return Result.success();
    }

    @Override
    public Result isInsert(Long userId) {
        UserCertification userCertification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId).eq("status", 1));
        if (userCertification != null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    public static Integer getAgeByCertId(String certId) {
        String birthday = "";
        if (certId.length() == 18) {
            birthday = certId.substring(6, 10) + "/"
                    + certId.substring(10, 12) + "/"
                    + certId.substring(12, 14);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date now = new Date();
        Date birth = new Date();
        try {
            birth = sdf.parse(birthday);
        } catch (ParseException e) {
        }
        long intervalMilli = now.getTime() - birth.getTime();
        int age = (int) (intervalMilli / (24 * 60 * 60 * 1000)) / 365;
        return age;
    }


    @Override
    public Result queryCertification(Long page, Long limit, String status, String name, Integer classify,
                                     Integer isRecommend, Integer onLine, String city, Integer classifyId,
                                     String longitude, String latitude,String shopName,String phone,Integer sort) {
        if(isRecommend==null){
            isRecommend=1;
        }
        if(page==null || limit==null){
            List<UserCertification> userCertifications = baseMapper.queryCertificationList(status, name, classify, isRecommend,
                    onLine, city, classifyId, longitude, latitude,shopName,phone);
            for (UserCertification userCertification : userCertifications) {
                if (userCertification != null) {
                    //关联用户
                    userCertification.setUserEntity(userDao.selectById(userCertification.getUserId()));
                }
            }
            return Result.success().put("data",userCertifications);
        }
        IPage<UserCertification> iPage1 = baseMapper.queryCertification(new Page<UserCertification>(page, limit),
                status, name, classify,isRecommend,onLine,city,classifyId,longitude,latitude,shopName,phone,sort);
        List<UserCertification> userCertifications = iPage1.getRecords();
        for (UserCertification userCertification : userCertifications) {
            if (userCertification != null) {
                //关联用户
                userCertification.setUserEntity(userDao.selectById(userCertification.getUserId()));
            }
        }
        return Result.success().put("data", new PageUtils(iPage1));
    }

    @Override
    public Result queryUserCertification(IPage iPage, String name, String phone, Integer classify,String shopName) {
        String nname = null;
        if (name != null && !(name.equals(""))) {
            nname = "%" + name + "%";
        }
        String nphone = null;
        if (phone != null && !(phone.equals(""))) {
            nphone = "%" + phone + "%";
        }

        return Result.success().put("data", baseMapper.queryUserCertification(iPage, nname, nphone, classify,shopName));
    }

    @Override
    public Result auditorUserCertification(Long status, Long id, String remek) {
        UserCertification userCertification = baseMapper.selectById(id);
        if (userCertification != null) {
            if (status == 1) {
                UserEntity userEntity = userDao.selectById(userCertification.getUserId());
                if (userCertification.getClassify() == 1) {
                    if (userEntity.getIsAuthentication() != null && userEntity.getIsAuthentication() == 2) {
                        userEntity.setIsAuthentication(3);
                    } else {
                        userEntity.setIsAuthentication(1);
                    }
                } else {
                    if (userEntity.getIsAuthentication() != null && userEntity.getIsAuthentication() == 1) {
                        userEntity.setIsAuthentication(3);
                    } else {
                        userEntity.setIsAuthentication(2);
                    }
                }
                userEntity.setShopImg(userCertification.getShopImg());
                userEntity.setShopName(userCertification.getShopName());
                userEntity.setShopType(userCertification.getShopType());
                userEntity.setLatitude(userCertification.getLatitude());
                userEntity.setLongitude(userCertification.getLongitude());
                userEntity.setAddress(userCertification.getAddress());
                userEntity.setAddressImg(userCertification.getAddressImg());
                userEntity.setStartTime(userCertification.getStartTime());
                userEntity.setEndTime(userCertification.getEndTime());
                userEntity.setShopPhone(userCertification.getPhone());
                userDao.updateById(userEntity);
            }
            userCertification.setStatus(status);
            userCertification.setRemek(remek);
            baseMapper.updateById(userCertification);
            return Result.success();
        } else {
            return Result.error("要审核的信息不存在！");
        }
    }

    @Override
    public Result queryInsert(Long userId) {
        return Result.success().put("data", baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId)));
    }

    @Override
    public UserCertification getCertificationInfo(Long userId) {
        UserCertification certification = baseMapper.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
        if (certification != null) {
            certification.setUserEntity(userDao.selectById(userId));

        }

        return certification;
    }

    @Override
    public Result updateCertification(UserCertification userCertification) {
        if (userCertification.getUserId() == null) {
            return Result.error("用户id不能为空");
        }
        return Result.upStatus(baseMapper.update(userCertification, new QueryWrapper<UserCertification>().eq("user_id", userCertification.getUserId())));

    }

    @Override
    public Result selectCertificationById(Long id,String longitude,String latitude){
        return Result.success().put("data",baseMapper.selectCertificationById(id, longitude, latitude));
    }

}
